<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <PageTools>
          <!-- 左边 -->
          <template #left>
            <!-- #left == slot="left" -->
            <span>总条数: {{ total }}</span>
          </template>
          <!-- 右边 -->
          <template slot="right">
            <el-button
              v-allow="'Excel-push'"
              type="warning"
              size="small"
              @click="$router.push('/employees/excel')"
            >导入excel</el-button>
            <el-button
              v-allow="'Excel-pull'"
              type="danger"
              size="small"
              @click="hExportExcel"
            >导出excel</el-button>
            <el-button
              v-allow="'add'"
              type="primary"
              size="small"
              @click="showDialog = true"
            >新增员工</el-button>
          </template>
        </PageTools>
      </el-card>

      <el-card style="margin-top: 10px">
        <el-table
          border
          :data="employees"
          :default-sort="{ prop: 'workNumber' }"
        >
          <el-table-column :label="$t('table.id')" type="index" :index="getIndex" />
          <el-table-column :label="$t('table.username')" prop="username" />
          <el-table-column :label="$t('table.avatar')">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
              <!-- <el-avatar :size="20" :fit="fill" :src="scope.row.staffPhoto" /> -->
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.jobNumber')" prop="workNumber" sortable />
          <el-table-column :label="$t('table.hireForm')">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.department')" prop="departmentName" />
          <el-table-column :label="$t('table.entryTime')" prop="timeOfEntry" sortable>
            <template slot-scope="scope">
              <span>{{ operatingTime(scope.row.timeOfEntry) }}</span>
              <!-- 时间戳 -->
            </template>
          </el-table-column>
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column :label="$t('table.actions')" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/?id=' + scope.row.id)"
              >
                {{ $t('table.view') }}
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(scope.row.id)"
              >{{ $t('table.AssignRoles') }}</el-button>
              <el-button
                v-allow="'del'"
                type="text"
                size="small"
                @click="del(scope.row.id)"
              >{{ $t('table.delete') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="end"
          style="height: 60px; margin-top: 15px"
        >
          <el-pagination
            background
            :page-sizes="[3, 5, 10]"
            :current-page.sync="curPage"
            :page-size="size"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 新增员工弹框 -->
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <EmpDialog
        v-if="showDialog"
        @close="close"
        @update-empolyee="hUpdateEmployee"
      />
    </el-dialog>

    <!-- 分配角色弹框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="showDialogRole"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <AssignRole
        v-if="showDialogRole"
        ref="assignRole"
        :cur-id="id"
        @close="showDialogRole = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './components/empDialog.vue'
import AssignRole from './assignRole'
// console.log(EmployeeEnum)

// forEach方法
// const obj = {}
// EmployeeEnum.hireType.forEach(it => {
//   obj[it.id] = it.value
// })

// ruduce方法
const obj = EmployeeEnum.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})

export default {
  components: {
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      curPage: 1,
      page: 1,
      size: 5,
      employees: [],
      total: 0,
      showDialog: false,
      showDialogRole: false,
      id: ''
    }
  },
  created() {
    this.loadEmployess()
  },
  methods: {
    async loadEmployess() {
      const res = await getEmployeesList(this.page, this.size)
      // console.log(res)
      this.employees = res.data.rows
      this.total = res.data.total
      this.curPage = this.page
    },
    // 删
    del(id) {
      this.$confirm('你确定要删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch((err) => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async doDel(id) {
      const res = await delEmployee(id)
      console.log(res)
      this.$message.success('删除成功')

      if (this.employees.length === 1) {
        this.page--
        if (this.page <= 0) {
          this.page = 1
        }
      }

      this.loadEmployess()
    },
    // 子传父关闭弹窗
    close() {
      this.showDialog = false
    },
    format(typeNum) {
      // console.log(typeNum)
      // EmployeeEnum.hireType:[{id:1,value:'正式'},{id:2,value:'非正式'}]
      // const item = EmployeeEnum.hireType.find(it => it.id === typeNum)
      // if (item) {
      //   return item.value
      // } else {
      //   return '未知'
      // }

      return obj[typeNum]
    },
    hUpdateEmployee() {
      this.showDialog = false
      if (this.total % this.size === 0) {
        this.page = this.total / this.size + 1
      } else {
        this.page = Math.floor(this.total / this.size) + 1
      }
      this.loadEmployess()
    },
    formatData(rows) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      console.log(rows)

      const enkeys = Object.keys(rows[0])
      const header = enkeys.map((enkeys) => map[enkeys])
      const data = rows.map((obj) => {
        const key = obj['formOfEmployment'] // 1, 2
        console.log(key)
        obj['formOfEmployment'] = EmployeeEnum.hireType[key - 1].value // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })
      console.log(enkeys, header, data)

      return { header, data }
    },
    async hExportExcel() {
      const res = await getEmployeesList(this.page, this.size)

      const { header, data } = this.formatData(res.data.rows)
      console.log(header, data)

      import('@/vendor/Export2Excel').then((excel) => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hCurrentChange(curPage) {
      this.page = curPage
      this.loadEmployess()
    },
    hSizeChange(curPage) {
      this.size = curPage
      this.loadEmployess()
    },
    getIndex(index) {
      return index + 1 + (this.page - 1) * this.size
    },
    // 时间戳
    operatingTime(timeDate) {
      return this.$moment(timeDate).format('YYYY-MM-DD')
    },
    // 用户点击了分配角色
    hAssignRole(id) {
      this.showDialogRole = true
      this.id = id
      // this.$nextTick(() => {
      //   this.$refs.assignRole.loadRoles().loadRolesList()
      // })
    }
  }
}
</script>
